package com.sxintelbox.serialPort;

public class HexStingUtil {
    private static final char[] DIGITS_HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
            'E', 'F' };


    public static byte[] hexStringToByte(String hex){
        int length = hex.length() / 2;
        byte[] result = new byte[length];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos+1]));
        }
        return result;
    }

    public static int bytesToInt(byte[] a){
        int ans=0;
        for(int i=0;i<4;i++){
            ans<<=8;//左移 8 位
            ans|=a[3-i];//保存 byte 值到 ans 的最低 8 位上
        }
        return ans;
    }

    private static byte toByte(char c){
        byte b = (byte) "0123456789ABCDEF".indexOf(c);
        return b;
    }

}
